<template>
  <div class="app-container">
    <div class="search-container">
      <search-form ref="queryFormRef" :model="queryParam" @search="handleQuery" @reset="handleResetQuery">
        <el-form-item label="关键字" prop="keywords">
          <el-input v-model="queryParam.keywords" placeholder="菜单名称" clearable @keyup.enter="handleQuery" />
        </el-form-item>
      </search-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button v-hasPerm="['menu:add']" type="success" @click="handleOpenAddDialog()"><template
            #icon><i-ep-plus /></template>
          新增</el-button>
        <el-button v-hasPerm="['menu:del']" type="danger" :disabled="selectionIds.length === 0"
          @click="handleDelete()"><i-ep-delete />删除
        </el-button>
      </template>

      <el-table v-loading="loading" :data="menuTableData" highlight-current-row row-key="menu_id"
        @selection-change="handleSelectionChange" :expand-row-keys="['1']" @row-click="handleRowClick" :tree-props="{
          children: 'children',
          hasChildren: 'hasChildren',
        }">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="菜单名称" min-width="200">

          <template #default="scope">
            <template v-if="scope.row.icon && scope.row.icon.startsWith('el-icon')">
              <el-icon style="vertical-align: -0.15em">
                <component :is="scope.row.icon.replace('el-icon-', '')" />
              </el-icon>
            </template>
            <template v-else-if="scope.row.icon">
              <svg-icon :icon-class="scope.row.icon" />
            </template>
            <template v-else>
              <svg-icon icon-class="menu" />
            </template>
            {{ scope.row.title }}
          </template>
        </el-table-column>

        <el-table-column label="类型" align="center" width="80">
          <template #default="scope">
            <el-tag v-if="scope.row.type === MenuTypeEnum.CATALOG" type="warning">目录</el-tag>
            <el-tag v-if="scope.row.type === MenuTypeEnum.MENU" type="success">菜单</el-tag>
            <el-tag v-if="scope.row.type === MenuTypeEnum.BUTTON" type="primary">按钮</el-tag>
          </template>
        </el-table-column>

        <el-table-column label="路由名称" align="left" width="150" prop="name" />

        <el-table-column label="路由路径" align="left" width="150" prop="path" />

        <el-table-column label="组件路径" align="left" width="250" prop="component" />

        <el-table-column label="权限标识" align="center" width="200" prop="permission" />

        <el-table-column label="状态" align="center" width="80">
          <template #default="scope">
            <el-tag v-if="scope.row.hidden === 1" type="info">隐藏</el-tag>
            <el-tag v-else type="success">显示</el-tag>
          </template>
        </el-table-column>

        <el-table-column label="排序" align="center" width="80" prop="menu_sort" />

        <el-table-column fixed="right" align="center" label="操作" width="200">
          <template #default="scope">
            <el-button v-if="scope.row.type === 0 || scope.row.type === 1" v-hasPerm="['menu:add']" type="primary" link
              size="small" @click.stop="handleOpenAddDialog(scope.row)">
              <i-ep-plus />新增
            </el-button>

            <el-button v-hasPerm="['menu:edit']" type="primary" link size="small"
              @click.stop="handleOpenEditDialog(scope.row)">
              <i-ep-edit />编辑
            </el-button>
            <el-button v-hasPerm="['menu:del']" type="danger" link size="small"
              @click.stop="handleDelete(scope.row.menu_id)"><i-ep-delete />
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!--表单数据-->
    <Form ref="menuFormRef" v-model="dialog.visible" :title="dialog.title" :menu-item="selectedItem"
      @close="handleCloseDialog" @submit="handleDialogSubmit" />
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Menu",
  inheritAttrs: false,
})

import MenuAPI, { MenuQuery, MenuForm, MenuVO } from "@/api/menu"
import { MenuTypeEnum } from "@/enums/MenuTypeEnum"
import { buildTree } from "@/utils";
import Form from "./form.vue";

const queryFormRef = ref(ElForm)
const menuFormRef = ref(ElForm)

const loading = ref(false)
const dialog = reactive({
  title: "新增菜单",
  visible: false,
})

// 查询参数
const queryParam = reactive<MenuQuery>({})
// 菜单表格数据
const menuTableData = ref<MenuVO[]>([])

// 选择表格的行菜单ID
const selectedItem = ref<MenuVO>({
  pid: 0
})

const selectionIds = ref<number[]>([])

// 查询
const handleQuery = () => {
  const queryCondition: QueryCondition = {}
  if (queryParam.keywords) {
    queryCondition.and = [{ field: 'title', op: 'like', value: `%${queryParam.keywords}%` }]
  }
  getMenuTree(queryCondition)
}
// 获取菜单树形结构
const getMenuTree = (queryCondition: QueryCondition = {}) => {
  loading.value = true
  MenuAPI.query(queryCondition).then((res) => {
    const { status, data } = res
    if (status === 200) {
      menuTableData.value = buildTree(data, 'menu_id', 'pid')
    }
  }).finally(() => {
    loading.value = false
  })
}

// 重置查询
const handleResetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

// 行点击事件
const handleRowClick = (row: MenuVO) => {
  // 记录表格选择的菜单ID，新增子菜单作为父菜单ID
  selectedItem.value = Object.assign({}, row)
}

/** 行复选框选中记录选中ID集合 */
const handleSelectionChange = (selection: any) => {
  selectionIds.value = selection.map((item: any) => item.menu_id)
}

/**
 * 新增表单弹窗
 */
const handleOpenAddDialog = (row?: MenuVO) => {
  dialog.title = "新增菜单"
  if (row) {
    selectedItem.value = {
      pid: row.menu_id
    }
  }
  dialog.visible = true
}
/**
 * 编辑表单弹窗
 */
const handleOpenEditDialog = (row: MenuVO) => {
  dialog.title = "编辑菜单"
  selectedItem.value = Object.assign({}, row)
  dialog.visible = true
}




/** 菜单保存提交 */
const handleDialogSubmit = () => {
  dialog.visible = false
  handleQuery()
}

// 删除菜单
const handleDelete = (menuId?: number) => {
  const menuIds = menuId ? [menuId] : selectionIds.value
  if (!menuIds) {
    ElMessage.warning("请勾选删除项")
    return
  }
  ElMessageBox.confirm("确认删除已选中的菜单以及对应的子菜单么?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    loading.value = true
    const deleteCondition: QueryCondition = {
      "_cond": { and: [{ field: "menu_id", op: "in", value: menuIds }] }
    }
    MenuAPI.deleteByCondition(deleteCondition).then((res) => {
      if (res.status === 200) {
        ElMessage.success("删除成功")
        handleQuery()
      }
    }).finally(() => {
      loading.value = false
    })
  })
}

// 关闭弹窗
const handleCloseDialog = () => {
  dialog.visible = false
}

onMounted(() => {
  handleQuery()
})
</script>
